package abel.wlmr.model.unit;

import java.util.ArrayList;
import java.util.List;

import abel.wlmr.model.WlmrBasePart;
import abel.wlmr.model.WlmrBaseUnit;
import abel.wlmr.model.WlmrDefaultUnit;
import abel.wlmr.model.WlmrException;
import abel.wlmr.model.type.DataIdBody;
import io.netty.buffer.ByteBuf;

/**
 * 数据单元标识
 * 数据单元
 * EC（见本附录 B.4.3.4.6.3）
 * Tp（见本附录 B.4.3.4.6.4）
 * 
 * F1 全部确认：对收到报文中的全部数据单元标识进行确认 p0
 * F2 全部否认：对收到报文中的全部数据单元标识进行否认 p0
 * F3 按数据单元标识确认和否认：对收到报文中的全部数据单元标识进行逐个确认/否认 p0
 * 
 * @author Abel
 *
 */
public class Afn00Part extends WlmrBasePart {

    public static final short F_CONFIRM = 1;
    public static final short F_DENY = 2;
    public static final short F_SOME = 3;

    /**
     * 
     */
    public Afn00Part() {
        super();
    }

    /**
     * @param guessedLen
     */
    public Afn00Part(short guessedLen) {
        super(guessedLen);
    }

    @Override
    public int parseBuf(ByteBuf buf) throws WlmrException {
        id = new DataIdBody();
        id.parseBuf(buf);
        short len = (short) (getGuessedLength() - DataIdBody.FIXED_LEN);

        // for p0:
        List<WlmrBaseUnit> units = new ArrayList<>();
        unitList.add(units);

        switch (id.getDt().firstType()) {
        case F_CONFIRM:
        case F_DENY:
            // empty unit.
            break;

        case F_SOME:

        {
            Afn00F3Unit unit = new Afn00F3Unit(len);
            int plen = unit.parseBuf(buf);
            if (plen < 0) {
                throw new WlmrException("not enough bytes for 00-F3");
            }

            len -= plen;
            units.add(unit);

            break;
        }

        default:

        {
            WlmrBaseUnit unit = new WlmrDefaultUnit(len);
            len -= unit.parseBuf(buf);
            units.add(unit);
        }
        }

        return getGuessedLength() - len;
    }

}
